Another Introduction to Programming with Java Book by Talbot Tim

Another Introduction to Programming with Java Book by Talbot Tim

Author:Talbot, Tim [Talbot, Tim]
Language: eng
Format: azw3, pdf
Published: 2016-04-04T16:00:00+00:00


Chapter 11: Static

You may have noticed that the static keyword is everywhere. But what does it mean? If something is static then it can only exist once. Or at least that's how I look at it. Members declared as static will only exist once within a program no matter how many instances of the class exist. So if you had a class called Dinosaur and it had a static variable called legs then, no matter if you have 1 or 100 instances of the class Dinosaur, there will only be one instance of the variable legs that is shared between all the Dinosaur classes.

In a nutshell, static members belong to a class instead of a specific instance. A big pain in the ass when writing small test modules, for example, where you want a couple of global variables available to you within the main() method is needing to declare those variables as static. This is because the very characteristics of a static member mean that a static method can only access static variables. You can also access non-static members within a static method if done through an instantiated object, of course. We'll see more on instantiation in the next chapter.

Anyway, quickly moving on. I just wanted to touch on static because it's seldom ever mentioned and you'll forever wonder why you can't access non-static variables from your main() method otherwise!



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.